import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '../stores/user';

const routes = [
  { 
    path: '/', 
    name: 'Home', 
    component: () => import('../views/Home.vue'),
    meta: { title: '首页' }
  },
  { 
    path: '/products', 
    name: 'ProductList', 
    component: () => import('../views/ProductList.vue'),
    meta: { title: '商品列表' }
  },
  { 
    path: '/product/:id', 
    name: 'ProductDetail', 
    component: () => import('../views/ProductDetail.vue'),
    meta: { title: '商品详情' }
  },
  { 
    path: '/product-management', 
    name: 'ProductManagement', 
    component: () => import('../views/ProductManagement.vue'),
    meta: { title: '商品管理', requiresAuth: true, requiresSeller: true }
  },
  { 
    path: '/cart', 
    name: 'Cart', 
    component: () => import('../views/Cart.vue'),
    meta: { title: '购物车', requiresAuth: true }
  },
  { 
    path: '/orders', 
    name: 'Orders', 
    component: () => import('../views/Orders.vue'),
    meta: { title: '我的订单', requiresAuth: true }
  },
  { 
    path: '/orders/:id', 
    name: 'OrderDetail', 
    component: () => import('../views/OrderDetail.vue'),
    meta: { title: '订单详情', requiresAuth: true }
  },
  { 
    path: '/payment/:orderId', 
    name: 'Payment', 
    component: () => import('../views/Payment.vue'),
    meta: { title: '订单支付', requiresAuth: true }
  },
  { 
    path: '/login', 
    name: 'Login', 
    component: () => import('../views/Login.vue'),
    meta: { title: '登录' }
  },
  { 
    path: '/register', 
    name: 'Register', 
    component: () => import('../views/Register.vue'),
    meta: { title: '注册' }
  },
  // 404路由应放在最后
  { path: '/:pathMatch(.*)*', redirect: '/' }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 商城系统`;
  }
  
  // 检查是否需要登录
  if (to.meta.requiresAuth) {
    const userStore = useUserStore();
    if (!userStore.isAuthenticated()) {
      next('/login');
      return;
    }
    
    // 检查是否需要卖家权限
    if (to.meta.requiresSeller && userStore.role !== 1 && userStore.role !== 2) {
      next('/');
      return;
    }
  }
  
  next();
});

// 路由切换动画
router.afterEach((to, from) => {
  // 可以在这里添加页面切换后的逻辑
  console.log(`从 ${from.path} 跳转到 ${to.path}`);
});

export default router;